package com.gutsyzhan.dynamicdatasourcespringbootstarter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.NamedThreadLocal;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Objects;

public final class DynamicDataSourceContextHolder {
    /**
     * 双端队列本质上就是一个栈
     */
    private static final ThreadLocal<Deque<String>> DATASOURCE_CONTEXT = NamedThreadLocal
            .withInitial(()->new ArrayDeque<>());

    private DynamicDataSourceContextHolder(){
        if(Objects.isNull(DATASOURCE_CONTEXT)){
            throw new RuntimeException("禁止反射创建");
        }
    }

    public static String getCurrentDataSource(){
        return DATASOURCE_CONTEXT.get().peek();
    }

    public static String addDataSource(String dds){
        String datasource = StringUtils.isEmpty(dds)? "":dds;
        DATASOURCE_CONTEXT.get().push(datasource);
        return datasource;
    }

    public static void removeCurrentDataSource(){
        Deque<String> deque = DATASOURCE_CONTEXT.get();
        deque.poll();
        if(deque.isEmpty()){
            DATASOURCE_CONTEXT.remove();
        }

    }
}
